<?php
/*
* Kusht Engine.
* ----
* The MIT License
* Copyright (c) 2010 Andrew Tutt
* ----
*/

/* Basic Connector Class
*
* Should only hold connection-related information regarding a connected user
* in a Telnet-like transaction environment
*/

class Connector {
	public static $top_id = 0;
}

class TelnetConnector {
public $id; 		/* This is a Connection ID, not a Game Object ID */
public $socket; 	/* This is the User's Socket */
public $server;		/* This is the Connector's Server */
public $handshake;  /* This is the User's Handshake Status */
public $user;		/* This is the user who owns this connection */
public $loggedin;   /* Is the Connector In the Stream or Entering It? */
// I.E. Is this person on their own thread or in the main thread?

private $buffer; /* For use with telnet */
	
function __construct($server, $socket) {
	$this->id 			= Connector::$top_id++;
	$this->loggedin 	= false;
	$this->handshake 	= false;
	$this->server 		= $server;
	$this->socket 		= $socket;
	$this->buffer		= "";
}

function send($msg, $wrapper = TEXT) {
	// This function can be overloaded to handle Telnet Styling internally
	
	$msg .= "\n\r";
	
	if (@socket_write($this->socket,$msg,strlen($msg))===FALSE) {
		$this->disconnect();
	}
}

function send_data($data) {
	if(array_key_exists("chatroom",$data)) {
		$this->send(current(current($data)));
	}
	
	// We cannot send data unfiltered to the Client. We have to build a Telnet Interpreter in order to send this data successfully. 
}

function show_welcome_screen() {
	loginMngr::show_welcome_screen($this);
}

function handle_input($buffer) {
	if($this->handshake===false) {
		$this->handshake = true;
		$this->show_welcome_screen();
		loginMngr::$loginSessions += array($this->id=>new loginSession($this));
		return;
	}
	
	//** This might be better as a separate function
	// Throw away emptiness
	if(trim($buffer)==="" && $this->buffer==="") { return; }
	
	// Implements Backspace
	if($buffer===chr(8) && $this->buffer!=="") { $this->buffer = substr($this->buffer,0,strlen($this->buffer)-1); return; }
	elseif($buffer===chr(8)) { return; }
	
	// Store, then throw away incomplete input
	if(!(stristr($buffer,"\n") || stristr($buffer,"\r"))) { $this->buffer .= $buffer; return; } 
	
	//**
	
	$msg = $this->buffer;
	$this->buffer = ""; // Reset the Buffer	
	
	if($this->loggedin===false) {
		loginMngr::$loginSessions[$this->id]->login($msg);
		return;
	}
	
	CmdHandler::splitCmd($this->user,$msg); /* This Data is Now Part of the Game */
}

function disconnect() {
	if($this->loggedin===false) {
		echo($this->socket." UNEXPECTED DISCONNECT.\n");
	}
	
	$this->server->disconnect($this->id,$this->socket); 
}

}

?>